package ua.edu.nuos.jeetraining2012.automator.services.bl.services.com;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import ua.edu.nuos.jeetraining2012.automator.core.vo.message.Message;
import ua.edu.nuos.jeetraining2012.automator.core.vo.message.MessageDestination;
import ua.edu.nuos.jeetraining2012.automator.core.vo.message.MessageSource;
import ua.edu.nuos.jeetraining2012.automator.services.bl.common.services.message.AbstractMessageService;
import ua.edu.nuos.jeetraining2012.automator.services.common.api.dao.http.JsonHttpClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * vk.com implementation
 * @author Timur Yarosh
 *         Date: 04.06.13
 *         Time: 0:27
 */
public class VkService extends AbstractMessageService {
    private final String ACCESS_API_URL = "https://api.vk.com/method/%s";
    private String token;

    public VkService(String token) {
        this.token = token;
    }

    @Override
    protected boolean isAuthorized() {
        return false;
    }

    @Override
    protected void authorize() {
        token = null; // get token
    }

    @Override
    protected void executeSendMessage(Message message, MessageDestination destination) {
        if (message.listBinaryData().length == 0) {
            sendPlainTextMessage(message, destination);
        } else {
            sendMessageWithAttachments(message, destination);
        }
    }

    @Override
    protected Message executeReceiveMessage(MessageSource source) {
        Message receivedMessage = null;
        if (source.getType() == Message.Type.PRIVATE_MESSAGE) {
            receivedMessage = receivePrivateMessage(source);
        }
        return receivedMessage;
    }

    private Message receivePrivateMessage(MessageSource source) {
        JSONObject response = null;
        String url = String.format(ACCESS_API_URL, "messages.get");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("out", "0"));
        params.add(new BasicNameValuePair("access_token", token));
        try {
            response = JsonHttpClient.post(url, params);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return getMessageFromJsonReponse(response);
    }

    private Message getMessageFromJsonReponse(JSONObject response) {
        return null; // TODO impl
    }

    private String makeAuthorizationUrl(String redirect_uri, int app_id, String display, String permissions, String auth_url) {
        return String.format(auth_url, app_id, permissions, redirect_uri, display);
    }

    private void sendPlainTextMessage(Message message, MessageDestination destination) {
        String url = String.format(ACCESS_API_URL, "messages.send");
        String uids = makeUidsValue(destination);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("uids", uids));
        params.add(new BasicNameValuePair("message", message.getText()));
        params.add(new BasicNameValuePair("access_token", token));
        try {
            JsonHttpClient.post(url, params);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private String makeUidsValue(MessageDestination destination) {
        StringBuilder addrBuilder = new StringBuilder();
        List<String> addressees = destination.getAddressees();
        for (String addressee : addressees) {
            addrBuilder.append(addressee);
            addrBuilder.append(",");
        }
        String addr = addrBuilder.toString();
        addr = (addr.endsWith(","))? addr.substring(0, addr.lastIndexOf(",")) : addr;
        return (addr.isEmpty()) ? null : addr;
    }

    private void sendMessageWithAttachments(Message message, MessageDestination destination) {
        String url = String.format(ACCESS_API_URL, "messages.send");
    }
}
